# coding=utf-8

"""
@Author: LiangChao
@Email: kevinleong1011@hotmail.com
@Desc: 
"""

from makit import fn


class Plugin:
    def __init__(self, plugin_object=None):
        self.plugin_object = plugin_object
        self.__func = None
        self._active = None

    def active(self, *args, **kwargs):
        if self._active is None:
            method = getattr(self.plugin_object or self, 'active', None)
            self._active = fn.run(method, *args, **kwargs) if method else True
        return self._active

    def __getattr__(self, item):
        v = getattr(self.plugin_object, item, None)
        if callable(v):
            self.__func = v
            return self
        return v

    def __call__(self, *args, **kwargs):
        if self._active is None:
            self._active = self.active(*args, **kwargs)
        if not self._active:
            return
        if self.__func:
            return fn.run(self.__func, *args, **kwargs)

    def __repr__(self):
        return f'<Plugin {self.name}>'


class PluginCaller:
    def __init__(self):
        self._plugins = []
        self.__method = None

    def __getattr__(self, item):
        self.__method = item
        return self

    def __call__(self, *args, **kwargs):
        assert self.__method, "Unknown method to call!"
        results = {}
        for p in self._plugins:
            method = getattr(p, self.__method, None)
            if method:
                results[p.name] = method(*args, **kwargs)
        return results

    def add_plugin(self, plugin):
        self._plugins.append(plugin)
